<template>
  <div id="timesheet" class="tiemsheets">
    <div class="title">Timesheets</div>
    <div class="content">
      <div class="top-handle">
        <router-link tag="button" type="button" class="add-button" to="/views/time/manage/timesheet/add">+ Add TimeSheets</router-link>
      </div>
      <div class="table-content" v-if="tableData">
        <Table class="table-panel" :columns="columns1" :data="tableData"></Table>
      </div>
      <div class="page-content">
        <Page v-if="timesheets && timesheets.pages>1" class-name="page"  :total="timesheets.count" :current="timesheets.page" @on-change="changePage"></Page>
      </div>
    </div>
    <!--add Timesheets-->
  </div>
</template>

<script>
  import Vue from 'vue';
  export default {
    name:"Timesheets",
    created(){
      this.init();
    },
    computed:{
      timesheets(){
        return this.$store.getters.timesheets;
      },
      timezoneList(){
        return this.$store.getters.timezoneList;
      },
    },
    watch:{
      timesheets(value){
        this.tableData = value.records;
      },
      'page.page'(){
        this.getTimesheets();
      },
    },
    data () {
      return {
        page:{
          pageSize:10,
          page:1
        },
        columns1: [
       /*   {
            title: 'Group',
            key: 'group',
            className:'group-column',
            renderHeader:function (column,index) {
              return `<Select class="group-select"><Option>manage</Option></Select>`
            }
          },*/
          {
            title: 'Employee',
            key: 'employeeName'
          },
          {
            title: 'HoursType',
            key: 'jobName'
          },
          {
            title: 'Day',
            key: 'day'
          },
          {
            title: 'Start Time',
            key: 'clockinCheckTime',
            render:function (row,column,index) {
              if(new Date(row.clockinCheckTime) != 'Invalid Date'){
                return moment(row.clockinCheckTime).format('HH:SS')
              }
              return row.clockinCheckTime;
            }
          },
          {
            title: 'End time',
            key: 'clockoutCheckTime',
            render:function (row,column,index) {
              if(new Date(row.clockoutCheckTime) != 'Invalid Date'){
                return moment(row.clockoutCheckTime).format('HH:SS');
              }
              if(row.clockoutCheckTime == 'Working'){
                  return `<span style="color:#78D000">${row.clockoutCheckTime}</span>`
              }
              return row.clockoutCheckTime;
            }
          },
          {
            title: 'Hours',
            key: 'jobHrs',
            render:function (row,column,index) {
              if(row.clockoutCheckTime == 'Working'){
                return `<span style="color:#78D000">${row.jobHrs}</span>`
              }
              return row.jobHrs;
            }
          },
          {
            title: 'Notes',
            key: 'note'
          },
          {
            title: 'Location',
            key: 'location'
          },{
            title:" ",
            className:'edit-column',
            render:function (row, column, index) {
              return  ` <i v-if="row.isLock == 0" class="iconfont edit-icon" @click="editTimesheet($event,${index})">&#xe665;</i> <i class="iconfont delete-icon" @click="deleteTimesheet(${row.id})">&#xe668;</i>`;
            }
          }
        ],
        tableData: [],
        editTimesheetModel:{},
      }
    },
    methods:{
      init(){
        this.getTimesheets();
        this.getAllTimezone();
      },
      getTimesheets(){
        this.$store.dispatch('getTimesheets',{employeeId:null,page:this.page});
      },
      getAllTimezone(){
        this.$store.dispatch('getAllTimezone');
      },
      addTimesheet(){

      },
      editTimesheet(e,index){
        var t = this;
        var $tr = $(e.target).parents('tr');
        if($tr.next().hasClass('edit-row')){
          $tr.parent().find('.edit-row').remove();
          return
        }else{
          $tr.parent().find('.edit-row').remove();
        }
        var editForm =`
      <Form  class="my-form" ref="formInline" v-model="editTimesheetModel" :label-width="110" label-position="left">
        <Row>
         <i-col class="form-item" span="10">
          <Form-item label="EMPLOYEE">
              <Input v-model="employeeName" readonly></Input>
            </Form-item>
          </i-col>
          <i-col class="form-item" span="10">
          <Form-item label="TYPE" :label-width="50">
              <span class="value-text">
              {{editTimesheetModel.jobType == 1?'Time In/Out':'Duration'}}
              </span>
          </Form-item>
          </i-col>
        </Row>
         <Row>
           <i-col class="form-item" span="10">
            <Form-item label="STATUS">
                <Checkbox  v-model="isCurrentWorking"><span class="value-text" style="margin-left: 20px">Curently working</span> </Checkbox>
              </Form-item>
            </i-col>
        </Row>
        <Row>
           <i-col class="form-item" span="10">
            <Form-item label="TIME IN">
            <Date-picker type="datetime" v-model="editTimesheetModel.clockinTime"  placeholder="select clock in time"></Date-picker>
                <!--<Date-picker class="l" type="date" placeholder="select date" style="width: 110px"></Date-picker>
                <Select class="l" style="width: 80px;margin-left: 5px">
                  <Option>ss</Option>
                </Select>
               <Select class="l" style="width: 80px;margin-left: 5px">
                  <Option>am</Option>
                  <Option>pm</Option>
                </Select>-->
              </Form-item>
            </i-col>
            <i-col class="form-item" span="9">
            <Form-item label="TIME OUT" v-if="!isCurrentWorking">
             <Date-picker type="datetime"  v-model="editTimesheetModel.clockoutTime"  placeholder="select clock out time"></Date-picker>
               <!-- <Date-picker class="l" type="date" placeholder="select date" style="width: 110px"></Date-picker>
                <Select class="l" style="width: 80px;margin-left: 5px">
                  <Option>ss</Option>
                </Select>
               <Select class="l" style="width: 80px;margin-left: 5px">
                  <Option>am</Option>
                  <Option>pm</Option>
                </Select>-->
              </Form-item>
            </i-col>
             <i-col class="form-item" span="5" >
              <Form-item label="TOTAL HOURS" :label-width="120">
              <Input v-model="editTimesheetModel.jobHrs" readonly>
              </Form-item>
            </i-col>
        </Row>
        <Row>
         <i-col class="form-item" span="10">
            <Form-item label="HOURS TYPE">
              <Input v-model="editTimesheetModel.jobType" >
            </Form-item>
          </i-col>
          <i-col class="form-item" span="10">
            <Form-item label="TIME ZONE">
             <Select v-model="editTimesheetModel.timeZoneId">
              <Option v-for="(item,key) in timezoneList" :value="item.timeId">{{item.timezoneId}} </Option>
            </Select>
            </Form-item>
          </i-col>
        </Row>
        <div class="text-right">
          <Button class="default-btn" @click="cancel" >Cancel</Button>
          <Button class="default-btn active" @click="done" type="primary" style="margin-left:20px">Done</Button>
        </div>
    </Form>`;
        var len = this.columns1.length;
        var tr = `<tr id="edit-row" class="edit-row animated fadeIn"><td  class="edit-cell" colspan="${len}">${editForm}</td></tr>`
        var render = Vue.compile(tr);
        var $parent = this;
        var editModel = {
          clockinTime:t.tableData[index].clockinTime,
          clockoutTime:t.tableData[index].clockoutTime,
          jobHrs:t.tableData[index].jobHrs,
          note:t.tableData[index].note,
          location:t.tableData[index].location,
          jobId:t.tableData[index].jobId,
          jobType:t.tableData[index].jobType,
          employeeId:t.tableData[index].employeeId,
          clockDate:null,
          timeZoneId:t.tableData[index].clockTimezone,
          id:t.tableData[index].id,
        }

        var editComponent = new Vue({
          render: render.render,
          data:function () {
            return {
              editTimesheetModel:editModel,
              isCurrentWorking:t.tableData[index].clockoutTime == null,
              timezoneList:t.timezoneList,
              employeeName:t.tableData[index].employeeName
            }
          },
          computed:{
            jobHours(){
              if(this.isCurrentWorking){
                return new Date().getTime() - new Date(this.editTimesheetModel.clockinTime).getTime();
              }else{
                return new Date(this.editTimesheetModel.clockoutTime).getTime() - new Date(this.editTimesheetModel.clockinTime).getTime();
              }
            }
          },
          watch:{
            isCurrentWorking(value){
              if(value){
                this.editTimesheetModel.clockoutTime = null;
              }
            },
            jobHours(value){
              var hour = parseInt(value/1000/3600);
              var min = parseInt(value/1000%3600/60);
              hour = hour<10?'0'+hour:hour;
              min = min<10?'0'+min:min;
              this.editTimesheetModel.jobHrs = hour+':' + min ;
            }
          },
          methods:{
            done(){
              var paramData = JSON.parse(JSON.stringify(this.editTimesheetModel));
              if(paramData.clockinTime){
                paramData.clockinTime = moment(paramData.clockinTime).format('YYYY-MM-DD HH:MM:SS');
              }
              if(paramData.clockoutTime){
                paramData.clockoutTime = moment(paramData.clockoutTime).format('YYYY-MM-DD HH:MM:SS');
              }
              if(paramData.jobHrs){
                paramData.jobHrs = parseFloat(paramData.jobHrs.replace(':','.'));
              }
              paramData.clockDate = moment(paramData.clockinTime).format('YYYY-MM-DD');
              t.$store.dispatch('saveTimesheet',paramData).then(
                ()=>{
                  this.$Message.success('update success');
                  t.getTimesheets();
                  $('#timesheet .table-panel').find('.edit-row').remove();
                }
              );
            },
            cancel(){
              $('#timesheet .table-panel').find('.edit-row').remove();
            }
          }
        });
        var  Cell = editComponent.$mount();
        $tr.after(Cell.$el);
      },
      deleteTimesheet(id){
        this.$Modal.confirm({
          title: 'Delete',
          content: '<p>Delete this timesheet?</p>',
          loading: true,
          onOk: () => {
            this.$store.dispatch('deleteTimesheet',{id:id}).then(
              () =>{
                this.$Modal.remove();
                this.$Message.info('delete success!');
                this.getTimesheets();
              }
            )
          }
        });
      },
      changePage(page){
        this.page.page = page;
      },
    }
  }
</script>


<style  rel="stylesheet/scss" type="text/css" lang="scss"  >
  @import "src/assets/css/variable";
  #timesheet{
    .content{
      .top-handle{
        margin-bottom: 20px;
        .add-button{
          width: 140px;
          height:34px;
          border:none;
          background: #009AFF;
          border-radius: 2px;
          outline: none;
          /*font-family: PingFangTC-Regular;*/
          font-size: 12px;
          color: #FFFFFF;
          cursor: pointer;
          &:hover{
            opacity: .8;
          }
        }
      }
      .table-content{
        .table-panel{
          .group-column{
            .group-select{
              width: 80px;
              vertical-align: middle;
              border: 1px $baseBorderColor solid;
            }
          }
          .edit-column {
            .iconfont{
              font-size: 18px;
              color: $baseColor;
              margin-right:12px ;
              vertical-align: middle;
              &:hover{
                opacity: .7;
              }
            }
          }
          .edit-row{
            .edit-cell{
              background-color: #fffeef;
              text-align: left;
              padding: 20px;
              .form-item{
                padding: 0 12px;
                .value-text{
                  /*font-family: PingFangTC-Regular;*/
                  font-size: 14px;
                  color: #325570;
                }
              }
            }
          }
        }
      }
    }
  }
</style>
